package com.jinjia.ordersys.controller;

import com.jinjia.ordersys.domain.Person;
import com.jinjia.ordersys.dto.UpdateBindPhoneDTO;
import com.jinjia.ordersys.service.*;
import com.jinjia.ordersys.util.ConstantUtil;
import com.jinjia.ordersys.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 登录认证-Controller
 * @Param:
 * @return:
 * @Author: fhz
 * @Date: 11:03 2018-12-17
 */
@Slf4j
@RestController
@Api(tags = "登录认证操作")
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private PersonService personService;

    @PostMapping("/login")
    @ApiOperation(value = "小程序登录")
    ResponseVo login(@RequestParam("code") String code) {
        if (StringUtils.isEmpty(code)) {
            return ResponseVo.warn("code参数为空");
        }
        log.info("js_code:  {}", code);
        UserLoginVo userLoginVo = authService.getUserLoginVo(code);
        log.info("login  userLoginVo:  {}", userLoginVo.toString());
        if (userLoginVo.getOpenId() != null && !"".equals(userLoginVo.getOpenId())) {
            return ResponseVo.ok("success", userLoginVo);
        } else {
            return ResponseVo.error("登录异常");
        }
    }

    @PutMapping("/info")
    @ApiOperation(value = "更改绑定人员信息")
    ResponseVo updateBindPersonInfo(@RequestBody UpdateBindPhoneDTO updateBindPhoneDto) {
        if (null == updateBindPhoneDto || null == updateBindPhoneDto.getPersonId()
                || null == updateBindPhoneDto.getOpenId()) {
            return ResponseVo.warn(ConstantUtil.PARAM_ISNULL);
        }
        Person person = personService.getPersonInfoByPersonId(updateBindPhoneDto.getPersonId());
        if (null == person) {
            return ResponseVo.warn(ConstantUtil.PERSON_IS_NULL);
        }
        log.info("人员原信息 person info:  {}", person);
        Person personParam = new Person();
        personParam.setPhone(updateBindPhoneDto.getNewPhoneNumber());
        personParam.setId(person.getId());
        personParam.setName(updateBindPhoneDto.getNewPersonName());
        int result = personService.updateOrBindPerson(personParam);
        if (result < 1) {
            return ResponseVo.warn(ConstantUtil.FAILED);
        }
        return ResponseVo.ok();
    }

}